package com.talent.service.admin.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.talent.common.exception.TalentException;
import com.talent.model.dto.LoginDto;
import com.talent.model.vo.LoginVo;
import com.talent.model.vo.SysMenuVo;
import com.talent.service.base.auth.bo.JwtTokenBo;
import com.talent.service.base.auth.fegin.Oauth2Feign;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hszhou
 * @Date: 2025/2/18 17:42
 * @Description: 登陆功能
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements ILoginService {


    private final Oauth2Feign oauth2Feign;

    private final StringRedisTemplate stringRedisTemplate;

    @Value("${basic.token:Basic dGFsZW50OjEyMzQ1Ng==}")
    private String basicToken;
    @Override
    public LoginVo login(LoginDto loginDto) {

        /*
         *1. token
         *2. 获取菜单
         *3. 获取权限
         */
        ResponseEntity<JwtTokenBo> login = oauth2Feign.login("password", loginDto.getUsername(), loginDto.getPassword(), "admin", basicToken);
        if(login.getStatusCode()!= HttpStatus.OK){
            throw new TalentException("登录失败");
        }
        JwtTokenBo jwtToken = login.getBody();

        //解析出主题是用户的id
        String accessToken = jwtToken.getAccessToken();
        Jwt decode = JwtHelper.decode(accessToken);
        String claims = decode.getClaims();
        JSONObject jsonObject = JSON.parseObject(claims);
        Long userId = jsonObject.getLong("user_name");

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(jwtToken.getAccessToken());
        loginVo.setRefreshToken(jwtToken.getRefreshToken());
        loginVo.setUserId(userId);
        //存储到
        stringRedisTemplate.opsForValue().set(accessToken,"",jwtToken.getExpiresIn(), TimeUnit.SECONDS);
        List<SysMenuVo> menus =new ArrayList<>();
        return loginVo;
    }
}
